import axios from "axios";
import { ElNotification } from "element-plus";

let firstV: any[] = []; //记录初始获得的 script 文件字符串
let currentv: any[] = []; //记录当前获得的 script 文件字符串
let checkVersionInterval: any = null;
let type: boolean = false;
// 获得的文件字符串类似这样 `<script src="/js/chunk-vendors.1234fff.js"></script>`

async function getHtml() {
  let res = await axios.get("/index.html?date=" + Date.now());
  if (res.status == 200) {
    let text = res.data;
    if (text) {
      // 解析 html 内容，匹配 script 字符串
      let reg = /<script([^>]+)><\/script>/gi;
      return text.match(reg);
    }
  }
  return [];
}
function isEqual(a: any, b: any) {
  return (a.length = Array.from(new Set(a.concat(b))).length);
}

export async function checkIfNewVersion() {
  firstV = await getHtml();

  checkVersionInterval && clearInterval(checkVersionInterval);

  checkVersionInterval = setInterval(async () => {
    currentv = await getHtml();
    console.log(firstV, currentv);
    // 当前 script hash 和初始的不同时，说明已经更新
    if (!isEqual(firstV, currentv)) {
      console.log("已更新");
      if (type) return;
      ElNotification({
        title: "更新提示",
        message: "检测到更新，请刷新页面",
        type: "success",
        duration: 0,
      });
      type = true;
    }
  }, 5000);
}

// 文档可见时检测版本是否更新
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    checkIfNewVersion();
  } else {
    checkVersionInterval && clearInterval(checkVersionInterval);
  }
});
